<?php

class MiActivityAction extends Action {
    //获取密友圈密友列表
    public function getActivityList($name='',$order="updateTime", $orderBy="desc", $start = 0, $limit = 25) {

        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];

        Session::switchCustomer(0);
        $MiActivityModel = M("miactivity");
        // $miactivity_type_db = M('miactivity_type');
        Session::switchCustomer($cid);
        if($name){
            $where["a.activityname"] = array("like", "%".$name."%");
        }
        $where["a.deleted"] = 0;
        $where["a.fromCustomerId"] = $cid;

        $arr = $MiActivityModel->alias('a')
        ->field('a.*,b.iconUrl,b.module,b.name')
        ->join('inner join wx_miactivity_type b on a.type = b.id')
        ->where($where)
        ->order("$order $orderBy")->limit("$start, $limit")->select();

        $time_now = date('Y-m-d H:i:s');
        foreach ($arr as $key => $value) {
            if($value['status'] == 1){
                if($time_now < $value['startTime']){
                    $value['activity_status'] = '尚未开始';
                }elseif($time_now > $value['endTime']){
                    $value['activity_status'] = '已经结束';
                }else{
                    $value['activity_status'] = '进行中';
                }
            }else{
                $value['activity_status'] = '停止';
            }
            $arr[$key] = $value;
        }
        if ($arr) {

            $count =$MiActivityModel
            ->where($where)
            ->count();

            Output::instance()->objArray($arr, $count);
        } else {
            Output::instance()->resultCode(code_success);
        }


    }
    public function getActivityType($name='',$order='id asc',$start=0,$limit=10){
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $miactivity_type_db = M("MiactivityType");

        $map = array();
        $map['a.deleted'] = 0;
        $map['a.name'] = array('like','%'.$name.'%');
        $map['b.customerId'] = $cid;

        if($limit > 0){
            $list = $miactivity_type_db->alias('a')
            ->field('deleted',true)
            ->join('left join wx_customer_module_group b on a.module = b.group')
            ->where($map)
            ->order($order)
            ->select();
            // echo $miactivity_type_db->_sql();
            // exit;
        }else{
            $list = $miactivity_type_db->alias('a')
            ->field('deleted',true)
            ->join('left join wx_customer_module_group b on a.module = b.group')
            ->where($map)
            ->order($order)
            ->limit($start.','.$limit)
            ->select();
        }
        if($list){
            $count =$miactivity_type_db->alias('a')
            ->join('left join wx_customer_module_group b on a.module = b.group')
            ->where($map)
            ->count();
            Session::switchCustomer($cid);
            Output::instance()->objArray($list, $count);
        }else{
            Session::switchCustomer($cid);
            Output::instance()->resultCode(code_success);
        }

    }

    public function getTongjiList($returnJson=true,$actId,$fullName="",$order="a.createTime", $orderBy="desc", $start = 0, $limit = 25){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $MiActivityModel = M("miactivity_vote_regpeople");
        Session::switchCustomer($cid);
        if($fullName) {
            $where["a.name"] = array("like", "%".$fullName."%");
        }
        $where["a.activityId"] = $actId;

        $arr = $MiActivityModel
        ->alias("a")
        ->join("wx_".$cid."_user_weixin_info c on c.openid=a.fromUserName")
        ->field("a.*,c.nickname,c.headimgurl")
        ->where($where)
        ->order("$order $orderBy")->limit("$start, $limit")->select();


        if ($arr) {

            $count =$MiActivityModel
            ->alias("a")
            ->join("wx_".$cid."_user_weixin_info c on c.openid=a.fromUserName")
            ->where($where)
            ->count();
            if($returnJson){
                Output::instance()->objArray($arr, $count);
            } else {
                return $arr;
            }
        } else {
            Output::instance()->resultCode(code_success);
        }
    }
    public function getTongjiCount($actId){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $MiActivityModel = M("miactivity_vote_regpeople");
        Session::switchCustomer($cid);
        $result=$MiActivityModel->query(
            "SELECT (SELECT COUNT(1) AS t1  FROM wx_miactivity_vote_regpeople a where activityId=".$actId." ) AS t1  ,"
            ."(SELECT COUNT(1) AS t1  FROM wx_miactivity_vote_votepeople a INNER JOIN wx_miactivity_vote_regpeople b ON b.id=a.rId where b.activityId=".$actId.") AS t2"
            );
        if($result && count($result) > 0){
            Output::instance()->object($result[0]);
        }
    }
    public function export($actId,$fullName="",$order="a.createTime", $orderBy="desc", $start = 0, $limit = 25){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $MiActivityModel = M("miactivity_vote_regpeople");
        Session::switchCustomer($cid);
        if($fullName) {
            $where["a.name"] = array("like", "%".$fullName."%");
        }
        $where["a.activityId"] = $actId;

        $arr = $MiActivityModel
        ->alias("a")
        ->join("wx_".$cid."_user_weixin_info c on c.openid=a.fromUserName")
        ->field("a.*,c.nickname,c.headimgurl")
        ->where($where)
        ->order("$order $orderBy")->limit("$start, $limit")->select();

        if ($arr) {

            $count =$MiActivityModel
            ->alias("a")
            ->join("wx_".$cid."_user_weixin_info c on c.openid=a.fromUserName")
            ->where($where)
            ->count();

            Output::instance()->objArray($arr, $count);
        } else {
            Output::instance()->resultCode(code_success);
        }
    }

    public function delete($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $MiModel = M("miactivity");
        // $ShareModel = M("mishare");
        // $MaterialModel = M("mishare_material");
        // $McommentModel = M("mirecomment");
        Session::switchCustomer($cid);
        $time = date("Y-m-d H:i:s");
        $data["deleted"] = 1;
        $result = $MiModel->where("id=$id")->save($data);
        //	echo $MiModel->getLastSql();
        // $MiModel->startTrans();
        if ($result) {
            // $sharewhere['module'] = 'miactivity';
            // $sharewhere['moduleId'] = $id;
            // $shareId = $ShareModel->where($sharewhere)->find();
            // Log::write("shareId:" . $ShareModel->getlastSql());
            // $mwhere['sId'] = $shareId['id'];
            // $result = $ShareModel->where($sharewhere)->delete();
            // Log::write("删除share:$result ". $ShareModel->getlastSql());
            // if ($result === false) {
            // 	$MiModel->rollback();
            // 	Output::instance()->resultCode(code_sql_error);
            // 	return false;
            // }
            // $result = $MaterialModel->where($mwhere)->delete();
            // Log::write("删除Material:$result ". $MaterialModel->getlastSql());
            // if ($result === false) {
            // 	$MiModel->rollback();
            // 	Output::instance()->resultCode(code_sql_error);
            // 	return false;
            // }
            // $result = $McommentModel->where($mwhere)->delete();
            // Log::write("删除comment:$result ". $McommentModel->getlastSql());
            // if ($result === false) {
            // 	$MiModel->rollback();
            // 	Output::instance()->resultCode(code_sql_error);
            // 	return false;
            // }else{
            // 	$MiModel->commit();
            Output::instance()->resultCode(code_success);
            //}
        }else {
            Output::instance()->resultCode(code_sql_error);
        }


    }




    public function getActivityById($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $MiActivityModel = M("miactivity");
        $miactivity_type_db = M('miactivity_type');
        Session::switchCustomer($cid);
        $condition["ma.id"] = array("eq",$id);
        $mi = $MiActivityModel
        ->alias('ma')
        ->field('ma.*,b.module')
        ->join(' left join wx_miactivity_type b on ma.type = b.id')
        ->where($condition)
        ->find();
        /*echo '<pre>';
        var_dump(json_decode($mi['jsonstr']));
        echo '<pre>';exit;*/
        if($mi){
            $jsonstr = json_decode($mi['jsonstr'],true);
            if($jsonstr['activity_index_img']['src']){
               $jsonstr['activity_index_img']['src'] = explode(',',$jsonstr['activity_index_img']['src']);
           }
           if($jsonstr['activity_rule_img']['src']){
            $jsonstr['activity_rule_img']['src'] = explode(',',$jsonstr['activity_rule_img']['src']);
        }
        if($jsonstr['activity_submit_tip']['src']){
            $jsonstr['activity_submit_tip']['src'] = explode(',',$jsonstr['activity_submit_tip']['src']);
        }
        
        $mi['jsonstr'] = $jsonstr;
    }
    if ($mi) {
        Output::instance()->object($mi);
    } else {
        Output::instance()->resultCode(code_success);
    }
}


public function saveActivity($id=NULL,$activityname=NULL, $vId=0,$description=NULL, $title=NULL,$description1=NULL, $title1=NULL,$startTime=NULL,$endTime=NULL,$status=NULL,$jsonstr=null,$picurl=NULL,$picurl1=null,$shareImgs1=null,$type=null,$isLimitCount=NULL,$limitCount=NULL,$accessTag=NULL){
    $retVal = Session::init();
    if (!$retVal) {
        Output::instance()->resultCode(code_access_denied);
        return;
    }
    $pid=$id;
    $cid = Session::$user["customerId"];
    Session::switchCustomer(0);
    $MiActivityModel = M("miactivity");
    $time = date("Y-m-d H:i:s");
    $data["fromCustomerId"] = $cid;
    $data["deleted"] = 0;
    $data["vId"] = $vId;
    if($isLimitCount != NULL){
        $data["isLimitCount"] = $isLimitCount;
    }
    if($limitCount != NULL){
        $data["limitCount"] = $limitCount;
    }
    if($description !=NULL){
        $data["description"]=$description;
    }
    if($title != NULL){
        $data["title"]=$title;
    }

    if($activityname != NULL){
        $data["activityname"] = $activityname;
    }


    if($startTime != NULL){
        $data["startTime"] = $startTime;
    }
    if($endTime != NULL){
        $data["endTime"] = $endTime;
    }


    if($status!=NULL){
        $data["status"] = $status;
    }

    if($picurl!=NULL){
        $data["picurl"] = $picurl;
    }



    if($type!=NULL){
        $data["type"] = $type;
    }
    if($jsonstr != NULL){
        $data["jsonstr"]= $jsonstr;
    }

    if($accessTag != NULL){
        $data["accessTag"] = $accessTag;
    }

    if($accessTag != NULL){
        $data["accessTag"] = $accessTag;
    }

    if($id) {
        if($type == 5){
           $dir = LOCAL_PIC_PATH.'scanforgiftcode';
           // echo $dir;
           // exit;
          $del_result =  $this->delFile($dir);
          $log_data =array();
          $log_data['dir'] = $dir;
          $log_data['del_result'] = $del_result;
          Log::write('删除文件数据：'.json_encode($log_data));
        }
        $resultPro = $MiActivityModel->where("id=$id")->save($data);;
        S('activity_info_'.$id.'_'.$cid,false);
    } else{
        $data["createTime"] = $time;
        $data["updateTime"] = $time;
        if(!$data['startTime']){
            $data['startTime'] = date('Y-m-d');
        }
        if(!$data['endTime']){
            if($type == 2){
                $data['endTime'] = date('Y-m-d',time()+4*3600*24);
            }else{
                $data['endTime'] = date('Y-m-d',time()+3600*24);
            }
        }
        if($type == 1){
            $data['activityname'] = '新建晒照片活动';
        }else if($type == 2){
            $data['activityname'] = '新建吐槽活动';
        }else if($type == 3){
            $data['activityname'] = '新建报名活动';
        }else if($type==4){
           $data['activityname'] = '新建抽奖活动';
        }else if($type== 5){
            $data['activityname'] = '新建扫码送礼活动';
        }
       $data['status'] = 1;
       $data['partakeCount'] = 0;
            //使用保存到活动类型表中的默认数据
       $actType_table = M('miactivity_type');
       $actType = $actType_table->where(array('id'=>$type))->getField('defaultData');

            //活动存在默认数据
       if($actType) {
        $defaultDate = json_decode($actType, true);
                //$data['activityname'] = $defaultDate['activityname'];
        $data['description'] = $defaultDate['description'];
        $data['title'] = $defaultDate['title'];
        $data['jsonstr'] = json_encode($defaultDate['jsonstr']);
        $data['picurl'] = $defaultDate['picurl'];
        $data['partakeCount'] = $defaultDate['partakeCount'];

        $resultPro = $MiActivityModel->add($data);
        $id = $resultPro;

    }else{
        $resultPro = $MiActivityModel->add($data);
    }
}

Session::switchCustomer($cid);
$resultBase = true;
$resultMeter = true;
if($resultPro!==false && $resultBase!==false && $resultMeter!==false) {
    $sql = $MiActivityModel->getLastSql();
    if (!$id) {
        R('Log/add',array('activityManage','','活动管理',op_add,$sql,'添加活动'));
    } else {
        R('Log/add',array('activityManage','','活动管理',op_update,$sql,'修改活动'));
    }
    Output::instance()->resultCode();
} else {

    Output::instance()->resultCode(code_sql_error);
}
}


/*删除指定目录下的文件，不删除目录文件夹*/
private function delFile($dirName){
    if(file_exists($dirName) && $handle=opendir($dirName)){
        while(false!==($item = readdir($handle))){
            if($item!= "." && $item != ".."){
                if(file_exists($dirName.'/'.$item) && is_dir($dirName.'/'.$item)){
                    $this->delFile($dirName.'/'.$item);
                }else{
                    if(unlink($dirName.'/'.$item)){
                        return true;
                    }
                }
            }
        }
        closedir( $handle);
    }
}

public function updateMiActivityProductTags($mId,$pIds){
    $retVal = Session::init();
    if (!$retVal) {
        Output::instance()->resultCode(code_access_denied);
        return;
    }
    $customerId = Session::$user["customerId"];
    Session::switchCustomer(0);
    $mpModel = M("miactivity_product_list");

    $pIds = explode(',',$pIds);
    $success = true;
    foreach ($pIds as $pId){
        $data['actId']=$mId;
        $data['pId']=$pId;
        $data['fromCustomerId']=$customerId;
            //判断是否已经在列表中了，防止重复添加
        $conditon['actId']=array('eq',$mId);
        $conditon['pId']=array('eq',$pId);
        $size=$mpModel->where($conditon)->find();
        if(count($size)<1){
            $success =$mpModel->add($data);
        }
    }
    Session::switchCustomer($customerId);
    if($success){
        Output::instance()->resultCode(code_success);
    }
}
public  function  deleteMiActivityPruduct($mId,$pId){
    $retVal = Session::init();
    if (!$retVal) {
        Output::instance()->resultCode(code_access_denied);
        return;
    }
    $customerId = Session::$user["customerId"];
    Session::switchCustomer(0);
    $uModel = M("miactivity_product_list");
    $condition['actId']=array('eq',$mId);
    $condition['pId']=array('eq',$pId);
    $condition['fromCustormerId']=array('eq',$customerId);
    $result=$uModel->where($condition)->delete();
    if($result){
        Output::instance()->resultCode(code_success);
    }else{
        Output::instance()->resultCode(code_sql_error);
    }
    Session::switchCustomer($customerId);
}
public function getProductByMiActivityId($mId){
    $retVal = Session::init();
    $cid = Session::$user["customerId"];
    Session::switchCustomer(0);
    $uModel = M("miactivity_product_list");
    Session::switchCustomer($cid);
    if (!$retVal) {
        Output::instance()->resultCode(code_access_denied);
        return;
    }
    $where['actId']=$mId;
    $arr = $uModel->alias('a')
    ->join("inner join wx_module_product b on a.pId=b.id")
    ->field("a.*,a.actId as mId,b.name,b.id as pId,b.fixedPrice as price")
    ->where($where)->select();
    if ($arr) {
        $count = $uModel->alias('a')
        ->join("inner join wx_module_product b on a.pId=b.id")
        ->field("a.*,b.name,b.id as pId,b.fixedPrice as price")
        ->where($where)
        ->count();
        Output::instance()->objArray($arr,$count);
    } else {
        Output::instance()->resultCode();
    }
}
public function getSummary($activity_id,$returnJson=true){
    $retVal = Session::init();
    if (!$retVal) {
        Output::instance()->resultCode(code_access_denied);
        return;
    }
    $cid = Session::$user["customerId"];
    Session::switchCustomer(0);
    $miactivity_partake_db = M('miactivity_partake');
    $miactivity_visit_db = M('miactivity_visit');
        // $map = array();
        // $map['a.activityId'] = $activity_id;
        // $map['a.cid'] = $cid;
        // $list = $miactivity_partake_db->alias('a')
        //     ->field('a.*,e.activityname,c.name as user_name,c.phone,c.picUrls,d.id as channel_id,d.name as channel_name,f.createTime as visit_time,f.id as visit_id,f.userId as visit_user_id')
        //     ->join('inner join '.C('DB_PREFIX').'miactivity_photo_share c on a.id=c.partakeId')
        //     ->join('left join '.C('DB_PREFIX').'miactivity_channel d on a.channelId=d.id')
        //     ->join('inner join '.C('DB_PREFIX').'miactivity e on a.activityId=e.id')
        //     ->join('left join '.C('DB_PREFIX').'miactivity_visit f on f.partakeId=a.id')
        //     ->where($map)->order('a.createTime asc')->select();
    $visit_count  = 0;
    $partake_count = 0;
    $partake_id = 0;
    $photo_count = 0;
    $channel_data = array();
    $date_data = array();

        // foreach ($list as $key => $value) {
        //     $activityname = $value['activityname'];
        //     $date_day = date('Y-m-d',strtotime($value['createTime']));
        //     $date_data[$date_day]['date_day'] = $date_day;

        //     if($value['channel_id']){
        //         $channel_data[$value['channel_id']]['channel_name'] = $value['channel_name'];
        //         $channel_data[$value['channel_id']]['channel_id'] = $value['channel_id'];
        //     }

        //     if($value['visit_id']){
        //         // $visit_count++;
        //         $visit_user_id = $value['visit_user_id'];
        //         if($value['channel_id']){
        //             if(!in_array($visit_user_id,$channel_data[$value['channel_id']]['user_id'])){
        //                 $channel_data[$value['channel_id']]['visit_count'] ++;
        //                 $channel_data[$value['channel_id']]['user_id'][] = $visit_user_id;
        //             }

        //         }
        //         if(!in_array($visit_user_id, $date_data[$date_day]['user_id'])){
        //             $date_data[$date_day]['visit_count']++;
        //             $date_data[$date_day]['user_id'][] =  $visit_user_id;
        //         }

        //     }

        //     if($partake_id != $value['id']){
        //         $photo_share_count = count(explode(',',$value['picUrls']));
        //         if($value['channel_id']){
        //             $channel_data[$value['channel_id']]['partake_count'] ++;
        //             $channel_data[$value['channel_id']]['photo_count'] =$channel_data[$value['channel_id']]['photo_count'] + $photo_share_count ;
        //         }
        //         $date_data[$date_day]['partake_count']++;
        //         $date_data[$date_day]['photo_count'] = $date_data[$date_day]['photo_count'] + $photo_share_count ;
        //         $partake_count++;
        //         $photo_count += $photo_share_count;
        //         $partake_id = $value['id'];
        //     }
        // }
        // foreach ($list as $key => $value) {
        //     if($value['visit_time']){
        //         $visit_user_id = $value['visit_user_id'];
        //         $date_day = date('Y-m-d',strtotime($value['visit_time']));
        //         if($date_data[$date_day]){

        //         }else{
        //             if(!in_array($visit_user_id, $date_data[$date_day]['user_id'])){
        //                 $date_data[$date_day]['visit_count']++;
        //                 $date_data[$date_day]['user_id'][] =  $visit_user_id;
        //             }
        //             // $date_data[$date_day]['visit_count'] ++;
        //             $date_data[$date_day]['date_day']  = $date_day;
        //         }
        //     }
        // }
        // foreach ($channel_data as $key => $value) {
        //     if(!$value['visit_count']){
        //         $value['visit_count'] = 0;
        //     }
        //     if(!$value['photo_count']){
        //         $value['photo_count'] = 0;
        //     }
        //     if(!$value['partake_count']){
        //         $value['partake_count'] = 0;
        //     }
        //     $channel_data[$key] = $value;
        // }
        // foreach ($date_data as $key => $value) {
        //     if(!$value['visit_count']){
        //         $value['visit_count'] = 0;
        //     }
        //     if(!$value['photo_count']){
        //         $value['photo_count'] = 0;
        //     }
        //     if(!$value['partake_count']){
        //         $value['partake_count'] = 0;
        //     }
        //     $date_data[$key] = $value;
        // }


    $sql = 'select count(*) as visit_count from (SELECT  userId  FROM `'.C('DB_PREFIX').'miactivity_visit` WHERE ( `cid` = '.$cid.' ) AND ( `activityId` = '.$activity_id.' ) AND ( `deleted` = 0 ) GROUP BY userId ) t ;';
    $visit_count_search = M()->query($sql);

    $visit_count = $visit_count_search[0]['visit_count'];

    $sql = 'select count(*) as partake_count from (SELECT  userId  FROM `'.C('DB_PREFIX').'miactivity_partake` WHERE ( `cid` = '.$cid.' ) AND ( `activityId` = '.$activity_id.' ) AND ( `deleted` = 0 ) GROUP BY userId ) t ;';
    $partake_count_search = M()->query($sql);
    $partake_count = $partake_count_search[0]['partake_count'];


    $sql = 'select sum(photoCount) as photo_count   FROM `'.C('DB_PREFIX').'miactivity_photo_share` WHERE ( `cid` = '.$cid.' ) AND ( `activityId` = '.$activity_id.' )   ;';
    $photo_count_search = M()->query($sql);
    $photo_count = $photo_count_search[0]['photo_count'];
        // echo $sql;
        // exit;
        // $photo_count = 100;
    $activityname = M('miactivity')->where('id='.$activity_id)->getField('activityname');
    $summary_data = array();
    $summary_data['partake_count'] = $partake_count;
    $summary_data['photo_count'] = $photo_count;
    $summary_data['visit_count'] = $visit_count;
        // $summary_data['channel_data'] = $channel_data;
        // $summary_data['date_data'] = $date_data;
    $summary_data['activityname'] = $activityname;
    if($summary_data){
        Session::switchCustomer($cid);
        if($returnJson==true){
            Output::instance()->object($summary_data);
        }else{
            return $summary_data;
        }

    }else{
        Output::instance()->resultCode();
    }

}
public function getDateChannelSummary($activity_id,$type='channel',$start=0,$limit=10,$returnJson=true){
    $retVal = Session::init();
    if (!$retVal) {
        Output::instance()->resultCode(code_access_denied);
        return;
    }
    $cid = Session::$user["customerId"];
    Session::switchCustomer(0);
    $miactivity_photo_share_db = M('miactivity_photo_share');
    $miactivity_visit_db = M('miactivity_visit');

    $channel_data = array();
    $date_data  = array();
    $summary_data =  array();
    $map = $visit_map = array();
    $map['cid'] = $cid;
    $map['activityId'] = $activity_id;
    $channel_map = array();
    $channel_map['cid'] = $cid;
    $channel_map['deleted'] = 0;
    switch ($type) {
       case 'channel':
       $miactivity_channel_db = M('miactivity_channel');
       $channel_list = $miactivity_channel_db->where($channel_map)->cache(true)->getField('id,name');
       if($returnJson==true){

        $channel_data = $miactivity_photo_share_db
        ->field('count(*) as partake_count, sum(photoCount) as photo_count,channelId')
        ->where($map)
        ->group('channelId')
        ->order('channelId asc')
        ->limit($start,$limit)
        ->select();

        $sql = 'select count(*) as count from (SELECT  channelId  FROM `'.C('DB_PREFIX').'miactivity_photo_share` WHERE ( `cid` = '.$cid.' ) AND ( `activityId` = '.$activity_id.' )  GROUP BY channelId ) t ;';
        $count_search = M()->query($sql);
        $count = $count_search[0]['count'];
                // echo $sql;
                // echo 'count='.$count.'<br/>';


    }else{
       $channel_data = $miactivity_photo_share_db
       ->field('count(*) as partake_count, sum(photoCount) as photo_count,channelId')
       ->where($map)
       ->group('channelId')
       ->order('channelId asc')
       ->select();

   }
   foreach ($channel_data as $key => $value) {
    if($value['channelId']){
        $channel_name = $channel_list[$value['channelId']]; 
        $value['channel_name'] =  $channel_name? $channel_name:'';
        $visit_map['channelId'] = $value['channelId'];
        $visit_map['cid'] = $cid;
        $visit_map['activityId'] = $activity_id;
        $visit_map['deleted'] = 0;
        $value['visit_count'] = $miactivity_visit_db->where($visit_map)->group('userId')->count();
    }else{
        $value['channelId'] = 0;
        $value['channel_name'] = '';
        $value['visit_count'] = 0;
    }
    if(!$value['photo_count']){
        $value['photo_count'] = 0;
    }
    if(!$value['partake_count']){
        $value['partake_count'] = 0;
    }
    $channel_data[$key] = $value;
}
$list = $channel_data;
break;
case 'day':
if($returnJson==true){
    $date_data = $miactivity_photo_share_db
    ->field("count(*) as partake_count, sum(photoCount) as photo_count,DATE_FORMAT(createTime,'%Y-%m-%d') as date_day")
    ->where($map)
    ->group('date_day')
    ->order('date_day asc')
    ->limit($start,$limit)
    ->select();
    $sql = "select count(*) as count from (SELECT DATE_FORMAT(createTime,'%Y-%m-%d') as date_day    FROM `wx_miactivity_photo_share` WHERE ( `cid` = $cid ) AND ( `activityId` = $activity_id )  GROUP BY date_day ) t ;";
    $count_search = M()->query($sql);
    $count = $count_search[0]['count'];
                // $count =  $miactivity_photo_share_db
                // ->field("count(*) as partake_count, sum(photoCount) as photo_count,DATE_FORMAT(createTime,'%Y-%m-%d') as date_day")
                // ->where($map)
                // ->group('date_day')
                // ->order('date_day asc')
                // ->count();
}else{
    $date_data = $miactivity_photo_share_db
    ->field("count(*) as partake_count, sum(photoCount) as photo_count,DATE_FORMAT(createTime,'%Y-%m-%d') as date_day")
    ->where($map)
    ->group('date_day')
    ->order('date_day asc')
    
    ->select();

}
foreach ($date_data as $key => $value) {
    $date_day = $value['date_day'];
    $visit_map['1'] = array('exp',"DATE_FORMAT(createTime,'%Y-%m-%d')=$date_day") ;
    $visit_map['cid'] = $cid;
    $visit_map['activityId'] = $activity_id;
    $visit_map['deleted'] = 0;
    $value['visit_count'] = $miactivity_visit_db->where($visit_map)->group('userId')->count();
    
    if(!$value['photo_count']){
        $value['photo_count'] = 0;
    }
    if(!$value['partake_count']){
        $value['partake_count'] = 0;
    }
    $date_data[$key] = $value;
}
$list = $date_data;
break;
}



$summary_data['channel_data'] = $channel_data;
$summary_data['date_data'] = $date_data;
if($list){
    Session::switchCustomer($cid);
    if($returnJson==true){
        Output::instance()->objArray($list, $count);
                // Output::instance()->object($summary_data);
    }else{
        return $summary_data;
    }

}else{
    Output::instance()->resultCode();
}
}

    /**
     * 晒照片活动数据导出
     */
    public function exportPhotoShare($actId,$type="day"){
        $result = array();
        $expTitle = '晒照片活动参与信息' ; //设置文件名
        $fileName = '晒照片活动参与信息' . date('Ymd'); //设置文件名
        $summary_data = $this->getDateChannelSummary($actId,$type,0,0,false);
        // R('MiActivity/getSummary', array($actId,false));
        Session::switchCustomer(0);
        $activity_name =  M('miactivity')->where('id='.$actId)->getField('activityname');
        //       echo json_encode($summary_data);
        //       exit;
        // var_dump($summary_data);
        // exit;
        switch ($type) {
            case 'day':
            $expCellName  = array(
                array('date_day','日期'),
                array('partake_count','参与人数'),
                array('photo_count','照片数'),
                array('visit_count','浏览人数'),
                );
            $expTableData = $summary_data['date_data'];
            $fileName = $activity_name.'_按日期统计_' . date('Ymd');
            break;
            case 'channel':
            $expCellName  = array(
                array('channel_name','渠道'),
                array('partake_count','参与人数'),
                array('photo_count','照片数'),
                array('visit_count','浏览人数'),
                );
            $expTableData = $summary_data['channel_data'];
            $fileName = $activity_name.'_按渠道统计_' . date('Ymd');
            break;
            default:

            break;
        }
        $expTableDataTemp = array();
        foreach ($expTableData as $key => $value) {
            $expTableDataTemp[] = $value;
        }
        // var_dump($expTableData);
        // exit;
        if($expTableDataTemp){
            Output::instance()->objArrayExcel($fileName,$expCellName,$expTableDataTemp);
        }
        // else{
        // 	$result['code'] = 0;
        // 	$result['info'] = '暂无数据';
        // 	Output::instance()->object($result);
        // }

        // if($expTableData){
        // 	$this->exportExcelNoTitle($fileName,$expTitle,$expCellName,$expTableData);
        // }


    }

 /*
    *获取活动参加记录
    */
 public function getPartakeList($activity_id,$keyword='',$channel_id=0,$order = 'id',$by='desc',$start = 0, $limit = 10){
    $retVal = Session::init();
    if (!$retVal) {
        Output::instance()->resultCode(code_access_denied);
        return;
    }
    $cid = Session::$user["customerId"];
    Session::switchCustomer(0);
    $miactivity_visit_db = M("miactivity_visit");
    $partake_db = M('miactivity_partake');
    $miactivity_channel_db = M('miactivity_channel');
    $miactivity_photo_share_db = M("miactivity_photo_share");
    $map = array();
    $map['c.activityId'] = $activity_id;
        // $map["a.deleted"] = 0;
    $map["c.cid"] = $cid;
    if($keyword&&$keyword != ''){
        $map['c.name|c.nickname|c.phone'] = array(array('like','%'.$keyword.'%'),array('like','%'.$keyword.'%'),array('like','%'.$keyword.'%'),'_multi'=>true);
    }

    if($channel_id > 0){
        $map['c.channelId'] = $channel_id;
    }

    $list = $miactivity_photo_share_db->alias('c')
    ->field('c.*, c.name as user_name')
            // ->join('inner join '.C('DB_PREFIX').'miactivity_photo_share c on a.id=c.partakeId')
            // // ->join('left join '.C('DB_PREFIX').'miactivity_channel d on a.channelId=d.id')
            // ->join('left join '.C('DB_PREFIX').$cid.'_user_weixin_info e  on a.userId=e.userId')
    ->where($map)
    ->distinct(true)
    ->order($order.' '.$by)->limit($start.', '.$limit)->select();

    $channel_map = array();
    $channel_map['cid'] = $cid;
    $channel_map['deleted'] = 0;
    $channel_list = $miactivity_channel_db->where($channel_map)->cache(true)->getField('id,name');

    $visit_map = array();
    foreach ($list as $key => $value) {
        $value['channel_name'] = $channel_list[$value['channelId']];
        $value['picUrls'] = explode(',', $value['picUrls']);
        $visit_map['partakeId'] = $value['partakeId'];
        $visit_map['activityId'] = $activity_id;
        $visit_map['cid'] = $cid;
        $visit_list = $miactivity_visit_db->where($visit_map)->group('userId')->select();
        $value['visit_count'] = count($visit_list);
        $list[$key] = $value;
    }

    if ($list) {
        $count =  $miactivity_photo_share_db->alias('c')
        ->field('c.*')
	            // ->join('inner join '.C('DB_PREFIX').'miactivity_photo_share c on a.id=c.partakeId')
	            // // ->join('left join '.C('DB_PREFIX').'miactivity_channel d on a.channelId=d.id')
	            // ->join('left join '.C('DB_PREFIX').$cid.'_user_weixin_info e  on a.userId=e.userId')
        ->where($map)
        ->distinct(true)
        ->count();
        Session::switchCustomer($cid);
        Output::instance()->objArray($list,$count);
    } else {
        Output::instance()->resultCode();
    }
}

    /*
    *获取活动参加记录
    */
    public function getPartakeList_backup($activity_id,$keyword='',$channel_id=0,$order = 'id',$by='desc',$start = 0, $limit = 10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $miactivity_visit_db = M("miactivity_visit");
        $partake_db = M('miactivity_partake');
        $miactivity_channel_db = M('miactivity_channel');

        $map = array();
        $map['activityId'] = $activity_id;
        $map["a.deleted"] = 0;
        $map["a.cid"] = $cid;
        if($keyword&&$keyword != ''){
            $map['c.name|e.nickname|c.phone'] = array(array('like','%'.$keyword.'%'),array('like','%'.$keyword.'%'),array('like','%'.$keyword.'%'),'_multi'=>true);
        }

        if($channel_id > 0){
            $map['a.channelId'] = $channel_id;
        }

        $list = $partake_db->alias('a')
        ->field('a.*,c.name as user_name,c.phone,c.picUrls,e.nickname,e.headimgurl')
        ->join('inner join '.C('DB_PREFIX').'miactivity_photo_share c on a.id=c.partakeId')
            // ->join('left join '.C('DB_PREFIX').'miactivity_channel d on a.channelId=d.id')
        ->join('left join '.C('DB_PREFIX').$cid.'_user_weixin_info e  on a.userId=e.userId')
        ->where($map)
        ->distinct(true)
        ->order($order.' '.$by)->limit($start.', '.$limit)->select();

        $channel_map = array();
        $channel_map['cid'] = $cid;
        $channel_map['deleted'] = 0;
        $channel_list = $miactivity_channel_db->where($channel_map)->cache(true)->getField('id,name');

        $visit_map = array();
        foreach ($list as $key => $value) {
            $value['channel_name'] = $channel_list[$value['channelId']];
            $value['picUrls'] = explode(',', $value['picUrls']);
            $visit_map['partakeId'] = $value['id'];
            $visit_map['activityId'] = $activity_id;
            $visit_map['cid'] = $cid;
            $visit_list = $miactivity_visit_db->where($visit_map)->group('userId')->select();
            $value['visit_count'] = count($visit_list);
            $list[$key] = $value;
        }

        if ($list) {
            $count = $partake_db->alias('a')
            ->field('a.*,c.name as user_name,c.phone,c.picUrls')
            ->join('inner join '.C('DB_PREFIX').'miactivity_photo_share c on a.id=c.partakeId')
                // ->join('left join '.C('DB_PREFIX').'miactivity_channel d on a.channelId=d.id')
            ->join('left join '.C('DB_PREFIX').$cid.'_user_weixin_info e  on a.userId=e.userId')
            ->where($map)
            ->distinct(true)
            ->count();
            Session::switchCustomer($cid);
            Output::instance()->objArray($list,$count);
        } else {
            Output::instance()->resultCode();
        }
    }

    /**
     * 获取对应活动的菜单数据
     * @param $activityTypeId 活动类型id
     * @param $activityId 活动id
     */
    public function getActivityMenus($activityTypeId, $activityId)
    {
        $relVal = Session::init();
        if (!$relVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $actType_table = M('miactivity_type');
        $moduleGroup_table = M('module_group');
        Session::switchCustomer($cid);
        //通过类型id获取到活动信息以及对应的区块信息
        $actMap = array();
        $actMap['id'] = $activityTypeId;
        $activity = $actType_table->where($actMap)->find();

        if (!$activity) {
            Output::instance()->object(array(
                'code' => 'error',
                'result' => '',
                'message' => '活动不存在!',
                ));
            return;
        }
        //循环数据进行href的拼装
        $menuInfo = json_decode($activity['menuJsonStr'], true);

        $resultMenu = array();
        if(count($menuInfo)<1){
            Output::instance()->object(array(
                'code' => 'error',
                'result' => '',
                'message' => '暂无菜单信息!',
                ));
            return;
        }

        $result = array();
        foreach($menuInfo as $keys=>$values){
            $result[$keys]['id'] = $values['id'];
            $result[$keys]['group'] = $values['group'];
            foreach($values['children'] as $key=>$value){
                $positionNum = strripos($value['url'], '/');
                $urlEnd = substr($value['url'],$positionNum);
                $urlStart = substr($value['url'],0,$positionNum);
                $value['url'] = $urlStart . '/' . $activityId . '/' . $activityTypeId .$urlEnd ;
                $value = self::rewirteMenu($value,$activityId,$activityTypeId);
                $result[$keys]['children'][] = $value;
            }

        }
        /*echo '<pre>';
            var_dump($menuInfo[0]['group']);
            echo '</pre>';exit;*/

            $datas = array();
            $datas['group'] = $menuInfo[0]['group'];
            $datas['activityTypeId'] = $activityTypeId;
            $datas['module'] = $activity['module'];
            $datas['activityId'] = $activityId;
            $datas['data'] = $result;

            if ($datas) {
                Output::instance()->object(array(
                    'code' => 'success',
                    'result' => $datas,
                    'message' => '获取数据成功',
                    ));
            } else {
                Output::instance()->object(array(
                    'code' => 'error',
                    'message' => '获取菜单数据失败',
                    'result' => ''
                    ));
            }
        }

    /**
     * 递归菜单及其子信息 拼接路径
     * @param $menuInfo 二级菜单信息
     * @param $activityId 活动id
     * @param $activityTypeId 活动类型id
     * @return array
     */
    protected function rewirteMenu(&$value,&$activityId,&$activityTypeId){
        if(count($value['children'])>0){
            foreach($value['children'] as $childK=>$val){
                $positionNum = strripos($val['url'], '/');
                $urlEnd = substr($val['url'],$positionNum);
                $urlStart = substr($val['url'],0,$positionNum);
                $val['url'] = $urlStart . '/' . $activityId . '/' . $activityTypeId .$urlEnd ;
                self::rewirteMenu($val,$activityId,$activityTypeId);
                $value['children'][$childK] = $val;
            }
        }
        return $value;
    }

    /**
     * 获取导出晒照片参与数据的任务结果
     * @param $taskName /任务名称
     */
    public function getSharePhotoTask($taskName){

        $relVal = Session::init();
        if(!$relVal){
            Output::instance()->object(code_access_denied);
        }

        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $taskQueue_table = M('task_queue');
        Session::switchCustomer($cid);

        //查询正在执行或者执行完成的任务
        $map['name'] = $taskName;
        $map['cid'] = $cid;
        //$map['status'] = array(array('eq',2),array('eq',3), 'or') ;
        $taskInfo = $taskQueue_table->where($map)->order('createTime desc')->find();
        /*echo '<pre>';
        var_dump($taskInfo);
        echo '</pre>';exit;*/
        if($taskInfo){
            if($taskInfo['status'] == 1){
                Output::instance()->object(array(
                    'code'=>0,
                    'msg'=>'正在等待执行!',
                    'data'=>''
                    ));
            }
            if($taskInfo['status'] == 2){
                Output::instance()->object(array(
                    'code'=>1,
                    'msg'=>'正在执行中!',
                    'data'=>''
                    ));
            }
            if($taskInfo['status'] == 3){
                //执行完成
                if($taskInfo['result']){
                    $downUrl = json_decode($taskInfo['result'], true)['downUrl'];
                    if($downUrl){
                        Output::instance()->object(array(
                            'code'=>2,
                            'msg'=>'执行成功!',
                            'data'=>array(
                                'taskId'=>$taskInfo['id'],
                                'downUrl'=>$downUrl,
                                'execute_end_time'=>$taskInfo['execute_end_time']
                                ),
                            ));
                    }
                }else{
                    Output::instance()->object(array(
                        'code'=>3,
                        'msg'=>'执行失败!',
                        'data'=>''
                        ));
                }
            }
            return;
        }

        Output::instance()->object(array(
            'code'=>-1,
            'msg'=>'未提交导出任务',
            'data'=>''
            ));

    }

    /**
     * 下载压缩好的zip文件
     * @param $taskId /任务id
     */
    public function getSharePhotoZip($taskId)
    {
        $relVal = Session::init();
        if (!$relVal) {
            Output::instance()->object(code_access_denied);
        }

        $cid = Session::init();
        Session::switchCustomer(0);
        $taskQueue_table = M('task_queue');
        Session::switchCustomer($cid);
        //获取下载URL
        $resultInfo = $taskQueue_table->where(array('id' => $taskId))->getField('result');
        $fileName = json_decode($resultInfo, true)['downUrl'];
        /* echo '<pre>';
         var_dump($fileName);
         echo '<pre>';exit;*/
         if (file_exists($fileName)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . basename($fileName) . '"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($fileName));
            readfile($fileName);
            exit;
        }
    }

    public function test(){
        self::getPartakeExcel([
            'param'=>'{"activity_id":141}',
            'id'=>3
            ]);
    }
    /**
     * 下载活动数据,一个渠道一个文件夹,每个文件夹包含Excel和所有的图
     * @param $taskInfo /整条任务信息
     * @return $bool
     */
    public function getPartakeExcel($taskInfo)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        set_time_limit(0) ;
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $miactivity_visit_db = M("miactivity_visit");
        $miactivity_channel_db = M('miactivity_channel');
        $miactivity_photo_share_db = M("miactivity_photo_share");
        $taskQueue_table = M('task_queue');
        Session::switchCustomer($cid);

        $param = json_decode($taskInfo['param'],true);
        $activity_id = $param['activity_id'];
        $map = array();
        $map['c.activityId'] = $activity_id;
        $map["c.cid"] = $cid;

        //查询所有渠道,循环每个渠道进行处理,避免数据过多造成内存不够等问题
        $channel_map = array();
        $channel_map['cid'] = $cid;
        $channel_map['deleted'] = 0;
        $channel_list = $miactivity_channel_db->where($channel_map)->getField('id,name');

        //无渠道
        $channel_list['0'] = '';
        //生成保存文件的文件夹
        $DirCommon = './Upload/user-'.$cid.'channelData';
        if(!is_dir($DirCommon)){
            self::createDir($DirCommon);
        }
        foreach($channel_list as $chKey=>$chVal){
            //单个渠道处
            $map["c.channelId"] = $chKey;
            if($chKey == 0){
                $map['c.channelId'] = array('EXP','IS NULL');
            }
            //查询所有的参与记录
            $list = $miactivity_photo_share_db->alias('c')
            ->field('c.id,c.name,c.nickname,c.phone,c.picUrls,c.createTime,c.channelId,p.ip_province')
            ->join('left join wx_miactivity_partake as p on c.partakeId=p.id ')
            ->where($map)
            ->distinct(true)
            ->select();
            //将参加数据按照渠道id区分组装成二维数组;
            $visit_map = $excelArr = $imgArr = array();
            $listCount = count($list);
            if(!$list){
                continue;
            }
            for($i=0;$i<$listCount;$i++){
                $channelId = $chKey;
                //保存图片数据
                $oneArr = [];
                $oneArr['img'] = explode(',', $list[$i]['picUrls']);
                $oneArr['id'] = $list[$i]['id'];
                $imgArr[] = $oneArr;

                //保存参与数据到Excel
                $list[$i]['channel_name'] = $channel_list[$channelId];
                $visit_map['partakeId'] = $list[$i]['partakeId'];
                $visit_map['activityId'] = $activity_id;
                $visit_map['cid'] = $cid;
                $visit_count = $miactivity_visit_db->where($visit_map)->group('userId')->count();
                $list[$i]['visit_count'] = $visit_count ? $visit_count : 0;
                unset($list[$i]['channelId']);
                unset($list[$i]['picUrls']);
                $excelArr[] = $list[$i];
            }

            //改成一维获取Excel
            $excelDirName = $DirCommon . '/' . $chKey;
            try {
                //创建目录
                if(!is_dir($excelDirName)){
                    self::createDir($excelDirName);
                }
                //保存Excel
                self::exportGetData($chKey, $excelArr, $excelDirName);
            } catch (Exception $e) {
                Log::write('任务执行失败-----------info111:' . $e->getMessage());
                continue;
            }
            //下载图片
            $imgDirName = $DirCommon . '/' . $chKey;
            if (count($imgArr) > 0) {
                for($n=0;$n<count($imgArr);$n++){
                    foreach ($imgArr[$n]['img'] as $imgKey => $imgVal) {
                        //文件名组成以单条数据编号加图片编号
                        $imgFileName = $imgDirName . '/' . $imgArr[$n]['id'] . '-' . $imgKey;
                        try {
                            self::getImage($imgVal, $imgFileName);
                        } catch (Exception $e) {
                            Log::write('任务执行失败-----------info222:' . $e->getMessage() . 'URL:' . $imgVal);
                            continue;
                        }
                    }
                }
            }
            //清空所占内存
            unset($list,$visit_map,$excelArr,$imgArr);
        }

        //压缩下载好的文件
        $zip = new ZipArchive();
        $downFileName = './Upload/user-'.$cid.'channelDataZip.zip';
        if ($zip->open($downFileName, ZipArchive::OVERWRITE) === TRUE) {
            //调用方法，对要打包的根目录进行操作，并将ZipArchive的对象传递给方法
            try {
                self::addFileToZip($DirCommon, $zip);
                //关闭处理的zip文件
                $zip->close();
                //将成功结果保存到任务表中
                $result = $taskQueue_table->where(array('id'=>$taskInfo['id']))->save(array(
                    'result'=>json_encode(array(
                        'code'=>1, //1代表成功
                        'downUrl'=>$downFileName
                        ))
                    ));
            } catch (Exception $e) {
                //压缩失败
                $result = $taskQueue_table->where(array('id'=>$taskInfo['id']))->save(array(
                    'result'=>json_encode(array(
                        'code'=>0, //0代表任务失败
                        'downUrl'=>''
                        ))
                    ));
                //echo $e->getMessage();
            }
            if(!is_numeric($result)){
                Log::write('任务执行失败------------SQL333:'.$taskQueue_table->getLastSql());
                throw new Exception('保存任务结果失败');
            }
        }

        //将文件删除,只保留zip
        self::delDir($DirCommon);
        return true;
    }

    /**
     * 删除文件夹
     * @param $dir /需要删除的文件路径
     */

    protected function delDir($dir){
        if (rmdir($dir)==false && is_dir($dir)) {
            if ($handle = opendir($dir)) {
                while (false !== ($filename = readdir($handle))) {
                    if ($filename == '..' || $filename == '.')   // 排除两个特殊目录
                    continue;
                    $path = $dir . '/' . $filename;
                    // 如果是目录，递归删除
                    if (is_dir($path)) {
                        self::delDir($path);
                    } else {
                        // 如果是文件，直接删除
                        unlink($path);
                    }
                }
            };
            // 关闭
            closedir($handle);
            //删除文件后删除空目录
            rmdir($dir);
        }else{
            throw new Exception('删除失败');
        }
    }

    /**
     * 压缩文件夹
     * @param $path /需要压缩的文件夹路径
     * @param $zip /PHP压缩类的对象
     */
    protected function addFileToZip($path, $zip)
    {
        $handler = opendir($path); //打开当前文件夹由$path指定。
        while (($filename = readdir($handler)) !== false) {
            //文件夹文件名字为'.'和‘..’，不要对他们进行操作
            if ($filename != "." && $filename != "..") {
                // 如果读取的某个对象是文件夹，则递归
                if (is_dir($path . "/" . $filename)) {
                    self::addFileToZip($path . "/" . $filename, $zip);
                } else { //将文件加入zip对象
                    $zip->addFile($path . "/" . $filename);
                }
            }
        }
        @closedir($path);
    }

    /**
     * 创建对应的文件夹
     * @param $save_dir /文件夹名称
     * @throws Exception
     */
    protected function createDir($save_dir)
    {
        //$save_dir = APP_PATH.'../updateDoc/datas';
        if (trim($save_dir) == '') {
            //保存的文件夹
            $save_dir = './';
        }
        if (0 !== strrpos($save_dir, '/')) {
            $save_dir .= '/';
        }
        //创建保存目录
        if (!file_exists($save_dir) && !mkdir(iconv('utf-8', 'gbk', $save_dir), 0777, true)) {
            //创建文件夹失败
            throw new Exception('创建文件夹失败');
        }
    }

    /**
     * 导出晒照片活动数据
     * @param $channelId /渠道id
     * @param $excelData /渠道数据
     * @param $excelDirName /保存单个渠道的文件夹
     */
    protected function exportGetData($channelId, $excelData, $excelDirName)
    {

        $fileName = $excelDirName . '/'. $channelId; //设置文件名
        $expCellName = array(
            array('id', '编号'),
            array('channel_name', '渠道'),
            array('nickname', '昵称'),
            array('name', '姓名'),
            array('ip_province', '省份'),
            array('phone', '手机号码'),
            array('createTime', '创建时间')
            );

        $expTableDataTemp = array();

        foreach ($excelData as $key => $value) {
            $expTableDataTemp[] = $value;
        }
        if ($expTableDataTemp) {
            self::objArrayExcel($fileName, $expCellName, $expTableDataTemp);
        }
    }


    /**
     * 输出Excel
     * @param $expCellName 表格数据描述，即表头
     * @param $expTableData 表格数据
     * @param $fileName 保存文件名
     */
    protected function objArrayExcel($fileName, $expCellName, $expTableData)
    {
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);

        vendor("PHPExcel.PHPExcel");
        $objPHPExcel = new PHPExcel();

        /** 导出数据量比较大, 这里设置超时时间无限制, 无论之前脚本运行多长时间, 此函数都会重启超时计时器, 从0重新计时 */
        set_time_limit(0);
        // 设置Excel文件缓存
        $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized;
        $cacheSettings = array('memoryCacheSize' => '8MB');
        PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        if ($expCellName && $expCellName !== '') {
            for ($i = 0; $i < $cellNum; $i++) {
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '1', $expCellName[$i][1]);
            }
            // Miscellaneous glyphs, UTF-8
            for ($i = 0; $i < $dataNum; $i++) {

                for ($j = 0; $j < $cellNum; $j++) {
                    $XS_SJ = $expTableData[$i][$expCellName[$j][0]];
                    //用' ' 处理数字为文本,以免excel中数字太大时科学计数法导致错误
                    $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 2), ' ' . $XS_SJ);//控制不能显示科学计数数字。
                }
            }
        } else {
            $i = 0;

            foreach ($expTableData as $key => $row) {
                $j = 0;
                if ($row["isNum"]) {
                    $isNum = explode(",", $row["isNum"]);
                    unset($row["isNum"]);
                }
                $title = $row['istitle'];
                if ($title && $title == 1) {
                    $expTableData[$key] = array_pop($row);
                }
                foreach ($row as $k1 => $cell) {
                    if ($title && $title == 1) {
                        $objPHPExcel->getActiveSheet(0)->getStyle($cellName[$j] . ($i + 1))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
                        $objPHPExcel->getActiveSheet()->getStyle($cellName[$j] . ($i + 1))->getFill()->getStartColor()->setARGB('00F0F0F0');
                        $objPHPExcel->getActiveSheet()->getRowDimension($i + 1)->setRowHeight(24);
                    }
                    if ($isNum && in_array($j, $isNum) && $i != 0) {
                        $objPHPExcel->getActiveSheet()->setCellValueExplicit($cellName[$j] . ($i + 1), ' ' . $cell, PHPExcel_Cell_DataType::TYPE_NUMERIC);
                    } else {
                        $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 1), ' ' . $cell);
                    }
                    $objPHPExcel->getActiveSheet()->getStyle($cellName[$j])->getAlignment()->setWrapText(true);
                    $objPHPExcel->getActiveSheet()->getStyle($cellName[$j] . ($i + 1))->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
                    $objPHPExcel->getActiveSheet()->getStyle($cellName[$j] . ($i + 1))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                    $objPHPExcel->getActiveSheet()->getColumnDimension($cellName[$j])->setWidth(18);
                    $objPHPExcel->getActiveSheet()->getRowDimension($i + 2)->setRowHeight(40);
                    $j++;
                }
                $i++;
            }
        }
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save($fileName . '.xls');
        //exit;
    }

    /**
     * 下载远程图片保存到指定文件夹
     * @param $url /图片远程url
     * @param string $filename /保存的文件路径
     * @return array 返回值
     * @throws Exception
     */
    protected function getImage($url, $filename = '')
    {
        if (trim($url) == '') {
            throw new Exception('图片路径不能为空');
        }

        if (trim($filename) !== '') {//保存文件名
            $ext = strrchr($url, '.');
            if ($ext != '.png' && $ext != '.jpg') {
                throw new Exception('图片后缀不符合要求');
            }
            $filename .= $ext;
        }
        /*echo '<pre>';
        var_dump($filename);
        echo '</pre>';exit;*/
        //获取远程文件所采用的方法
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $img = curl_exec($ch);
        curl_close($ch);
        if (!$img) {
            throw new Exception('获取图片失败');
        }
        $fp2 = @fopen($filename, 'a');
        if (!$fp2) {
            throw new Exception('打开图片失败');
        }
        fwrite($fp2, $img);
        fclose($fp2);
        unset($img, $url);
        return array('file_name' => $filename, 'save_path' => $filename, 'error' => 0);
    }
}
